<?php
namespace Wx\Controller;

use Think\Controller;
use Think\Model;

class OnlinePayController extends BaseController
{
    public function _initialize()
    {
        parent::_initialize();
    }    //首页

    //微信支付
    public  function wxPay(){

        $id=I('id');
        $type=I('type');
        $payid = '';
        // dump($id);
        // dump($type);
        // exit();
        //type 2充值 1订单
        $parms = explode('_', $_GET['id']);
        if (count($parms)==2) {
            $id = $parms[0];
            $type=$parms[1];
        }
        $money=0; 
        $title='';
        if($type==2){
            $orderId=M('orders_payid')->where(array('orderId'=>$id))->field('id')->select();
            $payid = $orderId[0]['id'];
            // dump($orderId);
            // dump($payid);
            $info=M('top_up')->where(array('topupNo'=>$orderId[0]['id']))->find();
            // dump($info);
            // exit();
            if(!$id||!$info||$info['status']==1){
                $this->redirect(U('User/recharge'));exit();
            }
            $title='充值';
            $money=$info['money'];
        }else{
            // dump($id);
            // exit();
            $orderId=M('orders_payid')->where(array('orderId'=>$id))->field('pid')->select();
            $payid = $orderId[count($orderId)-1]['pid'];
            // dump($orderId);
            // exit();
            $info=M('orders')->where(array('orderId'=>$id))->find();
            if(!$id||!$info||$info['orderStatus']==4){
                // $this->redirect(U('User/member'));exit();
            }
            // dump($info);
            // exit();
            // exit();
            $title='订单';
            $money=$info['needPay'];
        }
        vendor('WxPayPubHelper.WxPayPubHelper');
        $config = M('payments')->field('payName,payConfig')->where(array('payCode' => 'weixin', 'enabled' => 1))->find();
        $payConfig = json_decode($config['payConfig']);
        // dump($payConfig);
        // exit();
        if (!$config) {
            $this->error('未开启微信支付');
        }
        $jsApi = new \JsApi_pub($payConfig->appId, $payConfig->mchId, $payConfig->apiKey, $payConfig->appsecret);
        // dump($jsApi);
        //=========步骤1：网页授权获取用户openid============
        //通过code获得openid
        // dump('$_GET[code]');
        // dump($_GET['code']);
           //自定义订单号，此处仅作举例
        $out_trade_no = 'wx_'.$type.'_' . $id;
        if (isset($_GET['out_trade_no'])) {
            $out_trade_no = $_GET['out_trade_no'];
            // dump('out_trade_no');
            // dump($out_trade_no);
        }

        if (!isset($_GET['code'])) {
            //触发微信返回code码
            $id =$id.'_'.$type;
            $call_url = 'http://' . $_SERVER['HTTP_HOST'].'/index.php/Wx/OnlinePay/wxPay/id/'.$id;
           
            $url = $jsApi->createOauthUrlForCode(urlencode($call_url));

            Header("Location: $url");
        } else {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $jsApi->setCode($code);
            $openid = $jsApi->getOpenId();
        }
        //=========步骤2：使用统一支付接口，获取prepay_id============
        //使用统一支付接口
        //$unifiedOrder = new \UnifiedOrder_pub(C('WxPayConf_pub.APPID'),C('WxPayConf_pub.MCHID'),C('WxPayConf_pub.KEY'),C('WxPayConf_pub.APPSECRET'));
        $unifiedOrder = new \UnifiedOrder_pub($payConfig->appId, $payConfig->mchId, $payConfig->apiKey, $payConfig->appsecret);
        // dump($unifiedOrder);

        $shopName = M('sys_configs')->where(array('fieldCode'=>'mallTitle'))->getField('fieldValue');
        //设置统一支付接口参数
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //spbill_create_ip已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $unifiedOrder->setParameter("openid", $openid);//商品描述
        $unifiedOrder->setParameter("body", $shopName.$title.'商品');//商品描述
        $time=time();
        $timeStamp = (string)$time;
        $out_trade_no = $out_trade_no.'_'.$timeStamp;
        $money = 0.01;
        $unifiedOrder->setParameter("out_trade_no", $out_trade_no);//商户订单号
        $unifiedOrder->setParameter('total_fee',$money * 100);//总金额
        $unifiedOrder->setParameter("notify_url",'http://' . $_SERVER['HTTP_HOST'].'/index.php/Wx/OnlinePay/wxNotify');//通知地址
        $unifiedOrder->setParameter("trade_type", "JSAPI");//交易类型
        // dump($unifiedOrder);
        // exit();
        //非必填参数，商户可根据实际情况选填
        $prepay_id = $unifiedOrder->getPrepayId();
        // $prepay_id ='u802345jgfjsdfgsdg888';
        // dump('$prepay_id');
        // dump($prepay_id);
        //=========步骤3：使用jsapi调起支付============
        $jsApi->setPrepayId($prepay_id);

        $jsApiParameters = $jsApi->getParameters();
        // dump($jsApiParameters);
        // exit();
      
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('type',$type);
        $this->assign('payid',$payid);
        $this->assign('id',$id);
        $this->display('wxPay');
    }

    //微信支付的异步通知处理地址
    public function wxNotify(){
    
        D('Wx/OnlinePay')->wxNotify();
    }

    //支付宝支付
    public  function aliPay(){
        $id=I('id');
        $type=I('type'); $money=0; $title='';
        if($type==2){
            $info=M('top_up')->where(array('id'=>$id))->find();
            if(!$id||!$info||$info['status']==1){
                $this->redirect(U('User/recharge'));exit();
            }
            $title='充值';
            $money=$info['money'];
        }else{
            $info=M('orders')->where(array('orderId'=>$id))->find();
            if(!$id||!$info||$info['orderStatus']==4){
                $this->redirect(U('User/member'));exit();
            }
            $title='订单';
            $money=$info['needPay'];
        }
        vendor('Alipay.alipay_core');
        vendor('Alipay.alipay_md5');
        vendor('Alipay.alipay_notify');
        vendor('Alipay.alipay_submit');

        /*********************************************************
         * 把alipayapi.php中复制过来的如下两段代码去掉，
         * 第一段是引入配置项，
         * 第二段是引入submit.class.php这个类。
         * 为什么要去掉？？
         * 第一，配置项的内容已经在项目的Config.php文件中进行了配置，我们只需用C函数进行调用即可；
         * 第二，这里调用的submit.class.php类库我们已经在PayAction的_initialize()中已经引入；所以这里不再需要；
         *****************************************************/
        //这里我们通过TP的C函数把配置项参数读出，赋给$alipay_config；
        $alipay_config = C('alipay_config');
        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => 'alipay.wap.create.direct.pay.by.user',
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type"	=>1,
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
            "out_trade_no"	=>'wx_'.$type. '_' . $id . '_' . $alipay_config['seller_id'],
            "subject"	=> $title,
            "total_fee"	=> $money,
            "show_url"	=> '',
            //"app_pay"	=> "Y",//启用此参数能唤起钱包APP支付宝
            "body"	=> $title,
            //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
            //如"参数名"	=> "参数值"   注：上一个参数末尾需要“,”逗号。
        );
        //建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;
    }
    //支付宝充值及支付异步通知处理
    public  function  aliNotify(){
        D('Wap/OnlinePay')->aliNotify();
    }



    //余额支付
    public  function balancePay(){
        $orderId=I('orderId');
        $userId=session('userInfo.userId');
        $payPwd=I('payPwd');
        if(!$payPwd){
            $this->ajaxReturn(['status'=>-1,'msg'=>'请输入支付密码']);
        }
        $orderInfo=M('orders')->where(array('orderId'=>$orderId))->find();
        $userInfo=M('users')->where(array('userId'=>$userId))->find();
        if($orderInfo['orderStatus']==4||$orderInfo['isPay']==1){
            $this->ajaxReturn(['status'=>1,'msg'=>'订单已支付!']);
        }
        if($orderInfo['needPay']>$userInfo['userMoney']){
            $this->ajaxReturn(['status'=>-2,'msg'=>'余额不足,请选择其它付款方式!']);
        }
        if($userInfo['payPwd']==md5($payPwd.$userInfo['loginSecret'])){

            $res=D('Wap/OnlinePay')->balancePay($userInfo,$orderInfo);
            if($res){
                $this->ajaxReturn(['status'=>1,'msg'=>'支付成功']);
            }else{
                $this->ajaxReturn(['status'=>0,'msg'=>'支付失败']);
            }
        }else{
            $this->ajaxReturn(['status'=>-3,'msg'=>'支付密码不正确']);
        }

    }



}
